<html xmlns="http://www.w3.org/1999/xhtml"
>
<head>
    <title>ruben快乐阿超</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/index.css"/>
    <script type="application/javascript" src="js/index.js"></script>
</head>
<body>
<div class="box" id="loginForm">
    <h1>登录</h1>
    <input name="username" placeholder="用户名" type="text" value="rubenHappyAchao">
    <input name="password" placeholder="密码" type="password" value="Ruben8848">
    <input type="submit" placeholder="登录" onclick="submit()">
</div>
<script type="application/javascript">
    function submit() {
        var form = document.getElementById("loginForm");
        var elements = [];
        var tagElements = form.getElementsByTagName('input');
        for (var j = 0; j < tagElements.length; j++) {
            elements.push(tagElements[j]);
        }
        var user = {"username": "", "password": ""};
        elements.forEach(e => {
            if (e.name === "username") {
                user.username = e.value;
            } else if (e.name === "password") {
                user.password = e.value;
            }
        });
        var response = {
            say: {
                success: function (data) {
                    alert(data.data);
                    window.location.href = "/home.html"
                },
                error: function (data) {

                }
            },
            shout: {
                success: function (data) {
                    alert(data.msg);
                },
                error: function (data) {

                }
            },
            success: function (data) {
                var dataJson = {word: data.msg};
                localStorage.setItem("token", data.token);
                localStorage.setItem("refreshToken", data.refreshToken);
                // setCookie("token", data.token, 2)
                document.cookie = "token" + "=" + data.token + "; " + 30000;
                setCookie("refreshToken", data.refreshToken, 2)
                Ajax.get("/user/say", dataJson, this.say);
            },
            error: function (data) {
                alert(data.msg);
                Ajax.get("/user/shout", null, this.shout);
            }
        }
        Ajax.post("/user/login", JSON.stringify(user), response);

        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
    }
</script>
</body>
</html>
